package com.kuqi.core;

import android.app.Application;
import android.content.Context;
import android.os.Handler;
import android.os.Looper;
import android.os.Message;
import android.util.Log;
import androidx.annotation.NonNull;
import com.google.gson.reflect.TypeToken;
import com.kuqi.entitiy.BannerItem;
import com.kuqi.entitiy.Book;
import com.kuqi.entitiy.HomePageData;
import com.kuqi.entitiy.PromotionItem;
import com.kuqi.entitiy.ResultModel;
import com.kuqi.entitiy.StorePageData;
import com.kuqi.entitiy.UserInfo;
import com.kuqi.entitiy.VideoItem;
import com.kuqi.utils.JsonUtil;
import com.kuqi.utils.UrlTool;
import java.util.List;

// 全局app持久层参数控制
// 注意需要在manifest中进行注册，即application的name=this
public class ApplicationPersistent extends Application {

    // 构建完成即存储本单位对象
    private static ApplicationPersistent application;

    // 对应Http(或者本地环)命令指示关键字
    public static final int HANDLER_KEY_CHK = 10001; // 网络检测
    public static final int HANDLER_KEY_USER_LOGIN = 10010; // 用户登录
    public static final int HANDLER_KEY_HOME_DATA_BANNER = 1001101; // 主页信息_轮播
    public static final int HANDLER_KEY_HOME_DATA_MUSIC= 1001102; // 主页信息_音乐
    public static final int HANDLER_KEY_HOME_DATA_SCIENCE = 1001103; // 主页信息_科技
    public static final int HANDLER_KEY_HOME_DATA_CARTON = 1001104; // 主页信息_卡通
    public static final int HANDLER_KEY_STORE_DATA_PROMOTION = 1010001; // 书城信息_轮播
    public static final int HANDLER_KEY_STORE_DATA_LOVE = 1010002; // 书城信息_爱情
    public static final int HANDLER_KEY_STORE_DATA_TRAVEL = 1010003; // 书城信息_穿越
    public static final int HANDLER_KEY_STORE_DATA_MASTER = 1010004; // 书城信息_名著
    public static final int HANDLER_KEY_STORE_DATA_GAME = 1010005; // 书城信息_网游

    // 两个工作代理类
    private PersistentDataWorker dataWorker;
    private PersistentFuncWorker funcWorker;

    // 当前数据状态实体类
    private PersistentDataState dataState;


    // ==============下面时存储的状态信息=============
    private UserInfo userInfo; // 登录用户的信息
    private HomePageData homePageData; // home界面的数据内容
    private StorePageData storePageData; // store界面的数据内容

    @Override
    public void onCreate() {
        super.onCreate();
        application = this;
        dataWorker = new PersistentDataWorker();
        funcWorker = new PersistentFuncWorker();
        dataState = new PersistentDataState();
        homePageData = new HomePageData();
        storePageData = new StorePageData();
    }


    /**
     * 查询主页显示数据
     */
    public void searchHomeData() {
        dataWorker.searchHomeData(funcWorker, handler, userInfo);
    }

    /**
     * 查询书城显示数据
     */
    public void searchStoreData() { dataWorker.searchStoreData(funcWorker, handler, userInfo); }


    /**
     * 主线程执行
     * @param runnable
     */
    public void runOnUiThread(Runnable runnable) {
        handler.post(runnable);
    }


    /**
     * 获取程序根目录上下文
     * @return this
     */
    public Context getContext() {
        return application.getApplicationContext();
    }


    /**
     * 获取application对象
     * @return this
     */
    public static ApplicationPersistent getApplication() {
        return application;
    }


    /**
     * handler 数据回调处理方法
     */
    private Handler handler = new Handler(Looper.getMainLooper()){
        @Override
        public void handleMessage(@NonNull Message msg) {
            super.handleMessage(msg);
            if(msg.what == HANDLER_KEY_HOME_DATA_BANNER){ // 主页数据_轮播
                ResultModel result_banner = JsonUtil.getInstance().fromJson(msg.obj.toString(), ResultModel.class);
                if(result_banner.getCode() != -1){
                    String data_json = JsonUtil.getInstance().toJson(result_banner.getData());
                    List<BannerItem> list_data = JsonUtil.getInstance().fromJson(
                            data_json,
                            new TypeToken<List<BannerItem>>(){}.getType());
                    if(list_data.size() != 0){
                        for (BannerItem item:list_data) { // 调整且统一图像加载路径
                            item.setPicture(UrlTool.banner_base + item.getPicture());
                            homePageData.getBannerList().add(item);
                        }
                        dataState.setHomeDataState_banner(true);
                    }
                }else{
                    Log.e("获取轮播数据异常",result_banner.getMsg());
                }
            }else if(msg.what == HANDLER_KEY_HOME_DATA_MUSIC){ // 主页数据_音乐
                ResultModel result_video = JsonUtil.getInstance().fromJson(msg.obj.toString(), ResultModel.class);
                if(result_video.getCode() != -1){
                    String data_json = JsonUtil.getInstance().toJson(result_video.getData());
                    List<VideoItem> list_data = JsonUtil.getInstance().fromJson(
                            data_json,
                            new TypeToken<List<VideoItem>>(){}.getType());
                    if(list_data.size() != 0){
                        for (VideoItem item:list_data) { // 调整且统一图像加载路径
                            item.setThumbnail(UrlTool.video_base + item.getThumbnail());
                            item.setAddress(UrlTool.video_base + item.getAddress());
                            homePageData.getMusicList().add(item);
                        }
                        dataState.setHomeDataState_music(true);
                    }
                }else{
                    Log.e("获取视频数据异常",result_video.getMsg());
                }
            }else if(msg.what == HANDLER_KEY_HOME_DATA_SCIENCE){ //  主页数据_科技
                ResultModel result_science = JsonUtil.getInstance().fromJson(msg.obj.toString(), ResultModel.class);
                if(result_science.getCode() != -1){
                    String science_json = JsonUtil.getInstance().toJson(result_science.getData());
                    List<VideoItem> list_data = JsonUtil.getInstance().fromJson(
                            science_json,
                            new TypeToken<List<VideoItem>>(){}.getType());
                    if(list_data.size() != 0){
                        for (VideoItem item:list_data) { // 调整且统一图像加载路径
                            item.setThumbnail(UrlTool.video_base + item.getThumbnail());
                            item.setAddress(UrlTool.video_base + item.getAddress());
                            homePageData.getScienceList().add(item);
                        }
                        dataState.setHomeDataState_science(true);
                    }
                }else{
                    Log.e("获取视频数据异常",result_science.getMsg());
                }
            }else if(msg.what == HANDLER_KEY_HOME_DATA_CARTON){ // 主页数据_动画
                ResultModel result_carton = JsonUtil.getInstance().fromJson(msg.obj.toString(), ResultModel.class);
                if(result_carton.getCode() != -1){
                    String data_json = JsonUtil.getInstance().toJson(result_carton.getData());
                    List<VideoItem> list_data = JsonUtil.getInstance().fromJson(
                            data_json,
                            new TypeToken<List<VideoItem>>(){}.getType());
                    if(list_data.size() != 0){
                        for (VideoItem item:list_data) { // 调整且统一图像加载路径
                            item.setThumbnail(UrlTool.video_base + item.getThumbnail());
                            item.setAddress(UrlTool.video_base + item.getAddress());
                            homePageData.getCartonList().add(item);
                        }
                        dataState.setHomeDataState_carton(true);
                    }
                }else{
                    Log.e("获取视频数据异常",result_carton.getMsg());
                }
            }else if(msg.what == HANDLER_KEY_STORE_DATA_PROMOTION){
                ResultModel result_promotion = JsonUtil.getInstance().fromJson(msg.obj.toString(), ResultModel.class);
                if(result_promotion.getCode() != -1) {
                    String data_json = JsonUtil.getInstance().toJson(result_promotion.getData());
                    List<PromotionItem> list_data = JsonUtil.getInstance().fromJson(
                            data_json,
                            new TypeToken<List<PromotionItem>>() {
                            }.getType());
                    if (list_data.size() > 0) { // promotionImages
                        for (PromotionItem item : list_data) {
                            storePageData.getPromotionImages().add(UrlTool.banner_base + item.getPicture()); // 收集轮播图片连接
                        }
                        dataState.setStoreDataState_promotion(true);
                    } else {
                        Log.w("获取促销轮播图", "数量为空!");
                    }
                }
            }else if(msg.what == HANDLER_KEY_STORE_DATA_LOVE){
                ResultModel result_love = JsonUtil.getInstance().fromJson(msg.obj.toString(), ResultModel.class);
                if(result_love.getCode() != -1) {
                    String data_json = JsonUtil.getInstance().toJson(result_love.getData());
                    List<Book> list_data = JsonUtil.getInstance().fromJson(
                            data_json,
                            new TypeToken<List<Book>>() {
                            }.getType());
                    if (list_data.size() > 0) {
                        storePageData.getLoveList().addAll(list_data);
                        dataState.setStoreDataState_love(true);
                    } else {
                        Log.w("获取言情小说", "数量为空!");
                    }
                }
            }else if(msg.what == HANDLER_KEY_STORE_DATA_TRAVEL){
                ResultModel result_travel = JsonUtil.getInstance().fromJson(msg.obj.toString(), ResultModel.class);
                if(result_travel.getCode() != -1) {
                    String data_json = JsonUtil.getInstance().toJson(result_travel.getData());
                    List<Book> list_data = JsonUtil.getInstance().fromJson(
                            data_json,
                            new TypeToken<List<Book>>() {
                            }.getType());
                    if (list_data.size() > 0) {
                        storePageData.getTravelList().addAll(list_data);
                        dataState.setStoreDataState_travel(true);
                    } else {
                        Log.w("获取穿越小说", "数量为空!");
                    }
                }
            }else if(msg.what == HANDLER_KEY_STORE_DATA_MASTER){
                ResultModel result_master = JsonUtil.getInstance().fromJson(msg.obj.toString(), ResultModel.class);
                if(result_master.getCode() != -1) {
                    String data_json = JsonUtil.getInstance().toJson(result_master.getData());
                    List<Book> list_data = JsonUtil.getInstance().fromJson(
                            data_json,
                            new TypeToken<List<Book>>() {
                            }.getType());
                    if (list_data.size() > 0) {
                        storePageData.getMasterList().addAll(list_data);
                        dataState.setStoreDataState_master(true);
                    } else {
                        Log.w("获取名著小说", "数量为空!");
                    }
                }
            }else if(msg.what == HANDLER_KEY_STORE_DATA_GAME){
                ResultModel result_game = JsonUtil.getInstance().fromJson(msg.obj.toString(), ResultModel.class);
                if(result_game.getCode() != -1) {
                    String data_json = JsonUtil.getInstance().toJson(result_game.getData());
                    List<Book> list_data = JsonUtil.getInstance().fromJson(
                            data_json,
                            new TypeToken<List<Book>>() {
                            }.getType());
                    if (list_data.size() > 0) {
                        storePageData.getGameList().addAll(list_data);
                        dataState.setStoreDataState_game(true);
                    } else {
                        Log.w("获取网游小说", "数量为空!");
                    }
                }
            }else{
                // TODO 后续补充
            }
        }
    };


    public UserInfo getUserInfo() {
        return userInfo;
    }

    public void setUserInfo(UserInfo userInfo) {
        this.userInfo = userInfo;
    }

    public PersistentFuncWorker getFuncWorker() {
        return funcWorker;
    }

    public PersistentDataState getDataState() {
        return dataState;
    }

    public HomePageData getHomePageData(){
        return homePageData;
    }

    public StorePageData getStorePageData(){
        return storePageData;
    }


}
